package redisUtils

import (
	"errors"
	"fmt"
	redis "test/redis"
	"time"
)

const (
	KEY_PREFIX = "lock:"
)

type RedisModel struct {
	redis.BaseRedisModel
}

func (t *RedisModel) TryLocks(name string, time time.Duration) (bool, error) {
	//获取锁
	client, err := t.GetClient()
	if err != nil {
		return false, errors.New("获取redis实例失败：" + err.Error())
	}
	fmt.Printf("加锁时候的UUID：%s 用户Id：%s\n", 1, name)
	result, err := client.SetNX(KEY_PREFIX+name, 1, time).Result()
	return result, err
}

func (t *RedisModel) UnLocks(name string) error {
	var testModel RedisModel
	redis_client, err := testModel.GetClient()
	if err != nil {
		return errors.New("获取释放锁的redis实例失败: " + err.Error())
	}
	errs := redis_client.Del(KEY_PREFIX + name).Err()
	if errs != nil {
		return errors.New("释放锁失败：" + errs.Error())
	}

	return nil
}

/*
	枷锁
*/
func TryLock(name string, duration time.Duration) (bool, error) {

	var testModel RedisModel
	locks, err := testModel.TryLocks(name, duration)
	if err != nil {
		return false, err
	}
	return locks, err
}

/*
	释放锁
*/
func UnLock(name string) error {
	var testModel RedisModel
	err := testModel.UnLocks(name)
	return err
}
